<template>
  <div class="base-container" id="main">
    <t-form ref="form" :data="queryParams" label-width="80"
      @submit="() => { this.pagination.current = 1; this.queryParams.pageNum = 1; this.getList() }"
      @reset="() => { this.pagination.current = 1; this.queryParams.pageNum = 1; this.getList() }">
      <t-row style="border-bottom: 1px solid #E5E6EB;margin-bottom: 10px">
        <t-col :span="11" class="query-form-inline">
          <t-form-item label="项目名称" name="projectName">
            <t-input v-model="queryParams.projectName" clearable placeholder="请输入项目名称" style="width: 240px" />
          </t-form-item>
          <t-form-item label="申报单位" name="declareDeptName">
            <t-input v-model="queryParams.declareDeptName" clearable placeholder="请输入申报单位" style="width: 240px" />
          </t-form-item>
          <t-form-item label="项目状态" name="projectStatus">
            <t-select placeholder="请选择项目状态" style="width: 240px" clearable v-model="queryParams.projectStatus"
              :options="dict.type.sf_project_status">
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button theme="primary" type="submit"> 查询</t-button>
          <t-button theme="default" variant="outline" type="reset">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <div class="btn-group-inline">
      <t-button @click="apply" variant="outline" theme="primary">
        <t-icon name="add" slot="icon" />
        申报
      </t-button>
    </div>
    <t-table rowKey="index" size="small" :data="data" :columns="columns" hover :pagination="pagination"
      :loading="dataLoading" :sort="sort" :hideSortTips="true" @sort-change="sortChange">
      <template #projectName="{ row }">
        <t-link @click="dialog.objId = row.id; dialog.header = row.projectName; dialog.open_project_detail = true" hover="color"
          theme="primary">{{ row.projectName }}</t-link>
      </template>
      <template #adviceFunding="{ row }">
        {{ row.adviceFunding }}万元
      </template>
      <template #projectStatus="{ row }">
        <t-tag @click="dialog.header = row.projectName; dialog.objId = row.id; dialog.open_approve_list = true"
          class="cursor-pointer" :theme="handleTheme(row.projectStatus, dict.type.sf_project_status)" variant="light">
          {{ row.projectStatus | filterByDict(dict.type.sf_project_status) }}
        </t-tag>
        <br />
        <t-button v-if="['6', '7'].includes(row.projectStatus) && site_tag === 'jtt'" size="small" variant="text"
          theme="danger" class="t-button-link"
          @click="dialog.header = row.projectName; dialog.objId = row.id; dialog.open_expert_account_detail = true">导出专家账户信息</t-button>
      </template>
      <template #attributeDeptId="{ row }">
        {{ row.attributeDeptId | filterByTree(deptMenuOptions) }}
      </template>
      <template #manageDeptId="{ row }">
        {{ row.manageDeptId | filterByTree(deptMenuOptions) }}
      </template>
      <template #op="{ row }">

        <!-- <t-button @click="" size="small"
                  variant="text" class="t-button-link">
          <t-icon name="file-pdf" slot="icon"/>
          导出PDF
        </t-button> -->
        <t-button v-if="['1', '4', '10'].includes(row.projectStatus) || row.isReviewStatus === '1'"
          @click="update(row, 1)" size="small" variant="text" class="t-button-link">
          <t-icon name="edit-1" slot="icon" />
          {{ row.isReviewStatus === '1' ? '根据专家意见修改' : '继续申报' }}
        </t-button>
        <t-button size="small"
          @click="dialog.objId = row.id; dialog.header = row.projectName; dialog.open_current_project_detail = true"
          variant="text" class="t-button-link">
          <t-icon name="info-circle" slot="icon" />
          详情
        </t-button>
        <t-button v-if="['1'].includes(row.projectStatus)" theme="danger" @click="deleteProject(row)" size="small"
          variant="text" class="t-button-link">
          <t-icon name="delete" slot="icon" />
          删除
        </t-button>
        <t-button @click="createPDF(row)" size="small" variant="text" class="t-button-link">
          <t-icon name="file-pdf" slot="icon" />
          导出PDF
        </t-button>
      </template>
    </t-table>
    <project-detail-dialog tabDefaultValue="1" :header="dialog.header" :objId="dialog.objId"
      :visible.sync="dialog.open_project_detail" v-if="dialog.open_project_detail"></project-detail-dialog>
    <current-project-detail-dialog :header="dialog.header" :objId="dialog.objId"
      :visible.sync="dialog.open_current_project_detail"
      v-if="dialog.open_current_project_detail"></current-project-detail-dialog>
    <approve-list :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_approve_list"
      v-if="dialog.open_approve_list"></approve-list>
    <expert-account-detail-dialog :header="dialog.header" moduleName="kjsf" :objId="dialog.objId"
      :visible.sync="dialog.open_expert_account_detail"
      v-if="dialog.open_expert_account_detail"></expert-account-detail-dialog>

  </div>
</template>

<script>

import projectDetailDialog from "@/pages/kjsf/project/components/project-detail-dialog.vue";
import ApproveList from "@/pages/kjsf/approve/components/approve-list.vue";
import currentProjectDetailDialog from "./components/current-project-detail-dialog.vue"
import ExpertAccountDetailDialog from '@/pages/kjxm/apply/components/expert-account-detail-dialog.vue'

export default {
  name: "project-my",
  dicts: ["sf_project_status"],
  components: {
    projectDetailDialog,
    ApproveList,
    currentProjectDetailDialog,
    ExpertAccountDetailDialog

  },
  data () {
    return {
      applyLoading: false,
      site_tag: import.meta.env.VITE_SITE_TAG,
      dialog: {
        open: false,
        header: "",
        row: {},
        data: {},
        open_project_detail: false,
        open_outline_detail: false,
        open_contract_detail: false,
        open_current_project_detail: false,
        objId: 0,
        open_expert_account_detail: false,
        open_approve_list: false
      },
      nowRow: {},
      deleteVisible: false,
      deptMenuOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: "",
        declareDeptName: "",
        projectStatus: ""
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10, 20, 30, 50],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination, pageInfo)
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList()
        },
      },
      sort: [],
      dataLoading: false,
      columns: [
        {
          colKey: "projectName",
          title: "项目名称",
          align: "center",
          width: 220
        },
        {
          colKey: "adviceFunding",
          title: "投入经费",
          align: "center",
          width: 160,
        },
        // {
        //   colKey: "projectLeaderName",
        //   title: "项目负责人",
        //   align: "center",
        //   width: 160,
        // },
        {
          colKey: "manageDeptId",
          title: "主管单位",
          align: "center",
          width: 160,
        },
        // {
        //   colKey: "declareDeptName",
        //   title: "申报单位",
        //   align: "center",
        //   width: 160,
        // },
        {
          colKey: "declareDate",
          title: "申报日期",
          align: "center",
          width: 160,
          sorter: true,
        },
        {
          colKey: "startDate",
          title: "项目开始日期",
          align: "center",
          width: 160,
          sorter: true,
        },
        {
          colKey: "endDate",
          title: "项目结束日期",
          align: "center",
          width: 160,
          sorter: true,
        },
        {
          colKey: "projectStatus",
          title: "项目状态",
          align: "center",
          width: 160,
        },
        {
          colKey: "op",
          title: "操作",
          align: "center",
          width: 120,
          fixed: 'right'
        },
      ],
      data: []
    }
  },
  async created () {
    this.getList()
    this.getDeptTreeSelect()
  },
  methods: {
    createPDF (row) {
      const instance = this.$loading({
        fullscreen: true,
        attach: 'body',
        preventScrollThrough: false,
      });
      this.$api.kjsf.project.projectPDF(row.id).then(response => {
        window.open(response.data.fullFilePath, '_blank')
        instance.hide();
      }).catch((e) => {
        instance.hide();
        this.$message.error(e.toString());
      });
    },
    // 排序
    sortChange (sort) {
      this.sort = sort;
      let orderByColumn = []
      let isAsc = []
      if (sort instanceof Array) {
        orderByColumn = sort.map(val => val.sortBy)
        isAsc = sort.map(val => val.descending ? `desc` : `asc`)
      } else {
        orderByColumn = [sort.sortBy]
        isAsc = [sort.descending ? `desc` : `asc`]
      }
      this.queryParams.orderByColumn = orderByColumn.join(",")
      this.queryParams.isAsc = isAsc.join(",")
      this.getList();
    },
    // 获取接口数据
    getList () {
      this.dataLoading = true
      this.queryParams.pageNum = this.pagination.current || 1
      this.$api.kjsf.project.myDeclareList(this.queryParams).then(response => {
        this.pagination.total = response.total
        this.data = response.rows
        this.dataLoading = false
      }).catch(e => {
        this.dataLoading = false
        this.$message.error(e.toString())
      })
    },
    getDeptTreeSelect () {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data
      }).catch(e => {
        this.$message.error(e.toString())
      })
    },
    apply () {
      this.$router.push(`/kjsf/other/apply/project-apply/${Date.parse(new Date())}`);
    },
    // 编辑按钮
    update (row) {
      this.$api.kjsf.project.getAll(row.id).then(response => {
        const taskId = row.id;
        const activeFormList = [];
        sessionStorage.setItem(`${taskId}-step0`, row.id);
        sessionStorage.removeItem(`${taskId}-step1`);
        if (response.data.projectBackground && response.data.projectBackground.id) {
          sessionStorage.setItem(`${taskId}-step1`, response.data.projectBackground.id)
        } else {
          activeFormList.push(1);
        }
        sessionStorage.removeItem(`${taskId}-step2`);
        if (response.data.projectOverview && response.data.projectOverview.id) {
          sessionStorage.setItem(`${taskId}-step2`, response.data.projectOverview.id)
        } else {
          activeFormList.push(2);
        }
        sessionStorage.removeItem(`${taskId}-step3`);
        if (response.data.projectWorkBasis && response.data.projectWorkBasis.id) {
          sessionStorage.setItem(`${taskId}-step3`, response.data.projectWorkBasis.id)
        } else {
          activeFormList.push(3);
        }
        sessionStorage.removeItem(`${taskId}-step4`);
        if (response.data.projectMainContent && response.data.projectMainContent.id) {
          sessionStorage.setItem(`${taskId}-step4`, response.data.projectMainContent.id)
        } else {
          activeFormList.push(4);
        }
        sessionStorage.removeItem(`${taskId}-step5`);
        if (response.data.projectContentScale && response.data.projectContentScale.id) {
          sessionStorage.setItem(`${taskId}-step5`, response.data.projectContentScale.id)
        } else {
          activeFormList.push(5);
        }
        sessionStorage.removeItem(`${taskId}-step6`);
        if (response.data.projectGoal && response.data.projectGoal.id) {
          sessionStorage.setItem(`${taskId}-step6`, response.data.projectGoal.id)
        } else {
          activeFormList.push(6);
        }
        sessionStorage.removeItem(`${taskId}-step7`);
        if (response.data.projectCompanyList && response.data.projectCompanyList.length > 0) {
          sessionStorage.setItem(`${taskId}-step7`, response.data.projectCompanyList.length)
        } else {
          activeFormList.push(7);
        }
        if (activeFormList.length <= 0) {
          sessionStorage.setItem(`${taskId}-activeForm`, 8); // 跳转到最后一步
        } else {
          sessionStorage.setItem(`${taskId}-activeForm`, activeFormList[0]); // 跳转到第一个不满足
        }
        this.$router.push({
          path: `/kjsf/other/apply/project-apply/${taskId}`,
          query: { title: response.data.projectName }
        });

      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    deleteProject (row) {
      const confirmDia = this.$dialog.confirm({
        header: "系统提示",
        body: `是否确认删除项目名称为"${row.projectName}"的数据项？`,
        theme: "warning",
        onConfirm: ({ e }) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          this.$api.kjsf.project.delete(row.id).then(
            (res) => {
              this.getList();
              this.$message.success("删除成功");
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });
        }
      });
    },
  }
}
</script>

<style lang="less" scoped></style>
